package com.zhangyang.netty.register;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;


/**
 * Created by ASUS on 2017/9/24.
 * rpc的注册中心!
 */
public class RpcRegister {

    private int port;

    public RpcRegister(int port) {
        this.port = port;
    }

    /**
     * 对应的启动中心
     */
    public void start(){
        //boss 工作线程 服务大厅
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //work 工作线程 具体执行的任务
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            //设置服务端启动的入口
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                          .channel(NioServerSocketChannel.class)
                          .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    System.out.println("initChannel ........");
                    //进行往pipeLine 放入一些的东西
                    ChannelPipeline pipeline = socketChannel.pipeline();

                    //处理拆包和粘包的解码 编码器！
                    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
                    pipeline.addLast(new LengthFieldPrepender(4));

                    //加入jdk 序列化 的编码和解码!
                    pipeline.addLast("encoder",new ObjectEncoder());
                    pipeline.addLast("decoder",new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));

                    //加入自己的业务规则
                    pipeline.addLast(new RegisterHandler());
                }
            });

            //设置一些选项？？？？
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128).
                    childOption(ChannelOption.SO_KEEPALIVE, true);

            //进行绑定一些的端口 同步的操作
            ChannelFuture channelFuture=serverBootstrap.bind(this.port).sync();
            System.out.println("成功注册了 接口:"+this.port);
            //通道的同步
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            //进行 关闭
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String args[]) {
        new RpcRegister(8080).start();
    }
}
